package com.smi.service;

import java.io.*;

/**
 * @Author: yesiming
 * @Date: 下午1:17 2018/3/29
 */
public class FileUtil {
    static final String CONF_FILE = ".mysql-re.conf";
    static String CONF_FILE_PATH = null;
    static {
        try {
            CONF_FILE_PATH = homePath() + CONF_FILE;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * app打开时调用
     * @return
     * @throws IOException
     */
    public static String[] readLine() throws IOException {
        File file = new File(CONF_FILE_PATH);
        if (!file.exists()) {
            file.createNewFile();
            writeToFile("127.0.0.1",
                    "3306",
                    "demo",
                    "demo");
        }


        BufferedReader bf = new BufferedReader(new FileReader(CONF_FILE_PATH));
        String args = bf.readLine();
        bf.close();
        return args.split(",");
    }

    public static void writeToFile(String host,
                                   String port,
                                   String account,
                                   String password) throws IOException {

        File file = new File(CONF_FILE_PATH);
        OutputStream outputStream = null;

        outputStream = new FileOutputStream(file);
        StringBuffer content = new StringBuffer("");
        content.append(host);
        content.append(",");
        content.append(port);
        content.append(",");
        content.append(account);
        content.append(",");
        content.append(password);
        byte[] bs = content.toString().getBytes();
        outputStream.write(bs);
        outputStream.close();

    }

    static String homePath() throws IOException {
        String str = System.getProperty("user.dir");
        String[] arr = str.split("/");
        if(!"Users".equals(arr[1])) {
            // TODO: 提示app要放在用户目录下执行
        }
        return "/" + arr[1] + "/" + arr[2] + "/";
    }

    public static void main(String[] args) throws IOException {
        writeToFile("127.0.0.1",
                "3306",
                "demo",
                "demo");
    }
}
